#include "trigger.h"
#include "u.h"
#include <QDebug>
#include <QRandomGenerator>
#include <QThread>
#include "global.h"
#include "logmanager.h"

Trigger::Trigger(QObject *parent)
    : QThread(parent), m_level(0),m_bBuzzing(false)
{}

void Trigger::setBuzzing(bool bBuzzing)
{
    m_bBuzzing = bBuzzing;
}

bool Trigger::buzzing()
{
    if (m_bBuzzing){
        LogManager::ins().log(QtDebugMsg, QString("buzzing %1").arg(m_level));
        writeGpio(m_gpioBuzzing, m_level);
        m_level=!m_level;
    }
    return true;
}

bool Trigger::init(QString& err)
{
    do{
        // 导出GPIO
        if (!initGpio(m_gpioStop, "in")){
            err = "init gpio Stop in err";
            break;
        }
        if (!initGpio(m_gpioPowerOff, "in")){
            err = "init gpio PowerOff in err";
            break;
        }
        if (!initGpio(m_gpioBuzzing, "out")){
            err = "init gpio Buzzing in err";
            break;
        }
    }while(0);
    if(err.length() > 0){
        qDebug()<< "set gpio failure->" << err;
        return false;
    }
    return true;
}

bool Trigger::initGpio(int gpio, QString type)
{
    //QFile exportFile("/sys/class/gpio/export");
    QFile exportFile(Global::instance().getStr("Gpio-Dir") + "/export");
    if (exportFile.open(QIODevice::WriteOnly)) {
        exportFile.write(QString::number(gpio).toUtf8());
        exportFile.close();
    } else {
        qWarning() << __FILE__<< __LINE__<<"无法导出GPIO" << gpio;
        return false;
    }

    // 设置输入模式  /sys/class/gpio/gpio130/direction
    QFile directionFile(Global::instance().getStr("Gpio-Dir") + QString("/gpio%1/direction").arg(gpio));
    if (directionFile.open(QIODevice::WriteOnly)) {
        directionFile.write(type.toUtf8());
        directionFile.close();
        qDebug() << "GPIO" << gpio << type;
    }else{
        qWarning() << __FILE__<< __LINE__ << "无法导出GPIO" << gpio;
        return false;
    }
    return true;
}

bool Trigger::readGpio(int gpio)
{
    QFile valueFile(Global::instance().getStr("Gpio-Dir") + QString("/gpio%1/value").arg(gpio));

    if (!valueFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Failed to open GPIO value file" << gpio;
        return false;
    }

    QTextStream in(&valueFile);
    QString value = in.readLine().trimmed();
    valueFile.close();
    // LogManager::ins().log(QtMsgType::QtDebugMsg, QString("gpio:%1->value:%2").arg(gpio).arg(value));

    if (value.compare("1") == 0)
        return true;
    else
        return false;
}

bool Trigger::writeGpio(int gpio, int value)
{
    QFile valueFile(Global::instance().getStr("Gpio-Dir") + QString("/gpio%1/value").arg(gpio));
    if (!valueFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "Failed to open GPIO value file" << gpio;
        return false;
    }

    QTextStream out(&valueFile);
    out << value;
    valueFile.close();
    // LogManager::ins().log(QtMsgType::QtDebugMsg, QString("gpio:%1->value:%2").arg(gpio).arg(value));
    return true;
}



void Trigger::run()
{
    QString err;
    if (!init(err)){
        emit signalInfo(Global::Cmd::SetGPIO, Global::Result::Failure, err);
        return;
    }
    int i=0;
    int sleepInterval=100;
    while(true){
        if (readGpio(m_gpioStop) || readGpio(m_gpioPowerOff)){
            if (sleepInterval == 100){
                emit signalInfo(Global::Cmd::Emergency, Global::Result::Success, "trigger stop/poweroff");
                qDebug() << "set sleepInterval 2000 , m_timer.start";
                sleepInterval=2000;
            }
        }else{
            if (sleepInterval ==2000){
                emit signalInfo(Global::Cmd::EmergencyClear, Global::Result::Success, "trigger stop/poweroff");
                qDebug() << "set sleepInterval 100, m_timer.stop";
                sleepInterval=100;
            }
        }
        if (i>=5000){
            LogManager::ins().log(QtDebugMsg, "\tT running>");
            i = 0;
        }
        if (i%500 == 0) buzzing();


        QThread::msleep(100);
        i+=100;
    }
}
